
#include "Disk.h"
#include "BoundingBox.h"
#include "HitRecord.h"
#include "Point.h"
#include "Ray.h"
#include "Vector.h"
#include <math.h>

Disk::Disk(Material* material, const Point& center, const Vector& normal, double radius)
  : Primitive(material), center(center), my_normal(normal), radius(radius)
{
 my_normal.normalize();
  d = Dot(my_normal, Vector(center));
}

Disk::~Disk()
{
}

void Disk::getBounds(BoundingBox& bbox) const
{
  Vector diag(radius, radius, radius);
  bbox.extend(center+diag);
  bbox.extend(center-diag);
}

void Disk::intersect(HitRecord& hit, const RenderContext&, const Ray& ray) const
{
	double result = DBL_MAX;
	//determine the distance from the ray to the intersection
	double denominator = Dot(my_normal, ray.direction());
	if(abs(denominator) > EPSILON)
	{
		double t = (d - Dot(my_normal, Point::Point(ray.origin()))) / denominator;
		Point intersection = ray.origin() + ray.direction() * t;
		Vector r = intersection - center;
		if(r.length() < radius)
			if(t < result && t > EPSILON)
				hit.hit(t, this, matl);
	}
	return;
	
	
  
}

void Disk::normal(Vector& normal, const RenderContext&, const Point& hitpos,
                    const Ray& ray, const HitRecord& hit) const
{
  normal = my_normal;
}
